package com.simba.server.commands.impl.fetch;

import java.sql.ResultSet;
import java.util.ArrayList;

import com.simba.common.command.ICommand;
import com.simba.common.database.DbOperator;
import com.simba.server.components.data.BarcodeInfo;
import com.simba.server.components.data.SortInfo;

public class FetchInfoByBarcodeCmd implements ICommand
{
	public static final String NAME = "FetchInfoByBarcodeCmd";
	private final BarcodeInfo barcodeInfo;
	private final String columns = ""
			+ "barcode,droppedSlot,boxCode, errorCodeSVR,errorCodePLC,uploadFlag, uploadNum, planId, " +
			"roadSlot, roadSlotName,weight,length,width,height,volume";
	private String sql = "SELECT "+columns+" FROM tt_packet_off_info WHERE barcode=?";

	public FetchInfoByBarcodeCmd(BarcodeInfo barcodeInfo)
	{
		this.barcodeInfo = barcodeInfo;
	}

	@Override
	public String getName()
	{
		return FetchInfoByBarcodeCmd.NAME;
	}

	@Override
	public Boolean run(Object params)
	{
		Boolean ret = false;

		if (!(params instanceof DbOperator))
		{
			return ret;
		}

		if (barcodeInfo == null)
		{
			return ret;
		}

		if (barcodeInfo.getSortInfos()==null)
		{
			barcodeInfo.setSortInfos(new ArrayList<>());
		}

		try
		{
			DbOperator dbOperator = (DbOperator) params;
			dbOperator.prepareStatement(this.sql);
			dbOperator.setString(1, barcodeInfo.getBarcode());

			ResultSet rs = dbOperator.executeQuery();

			while (rs.next())
			{
				SortInfo info = new SortInfo();
				info.setBarcode(rs.getString("barcode"));
				info.setDroppedSlotId(rs.getInt("droppedSlot"));
				info.setBoxCode(rs.getString("boxCode"));
				info.setErrorCodeSVR(rs.getInt("errorCodeSVR"));
				info.setErrorCodePLC(rs.getInt("errorCodePLC"));
				info.setUploadFlag(rs.getInt("uploadFlag"));
				info.setUploadNum(rs.getInt("uploadNum"));
				info.setPlanId(rs.getString("planId"));
				info.setRoadSlot(rs.getString("roadSlot"));
				info.setRoadSlotName(rs.getString("roadSlotName"));
				info.setChargeWeight(rs.getString("weight"));
				info.setLength(rs.getString("length"));
				info.setWidth(rs.getString("width"));
				info.setHeight(rs.getString("height"));
				info.setVolume(rs.getString("volume"));

				barcodeInfo.getSortInfos().add(info);
			}
			ret = true;
		}
		catch (Exception ex)
		{
			ret = false;
		}

		return ret;
	}
}
